import { login } from '@/api/user'
import { getToken, setToken, removeToken, getName, setName, removeName, setAccount, getAccount, removeAccount, removeButtonpermsStr } from '@/utils/auth'
import { Promise } from 'q'
const state = {
  token: getToken(),
  name: getName(),
  account: getAccount()
}
const mutations = {

  SET_TOKEN: (state, token) => { // 设置token
    state.token = token
  },
  SET_NAME: (state, name) => { // 设置名字
    state.name = name
  },
  SET_ACCOUNT: (state, account) => { // 设置账户类型
    state.account = account
  }
}
const actions = {
  // 登录
  login({ commit }, userInfo) {
    const { username, password, input, imgNum } = userInfo
    return new Promise((resolve, reject) => {
      login({ user_name: username.trim(), user_pass: password, img_code: input, math_code: imgNum }).then(response => {
        commit('SET_TOKEN', response.token)
        commit('SET_NAME', username)
        commit('SET_ACCOUNT', response.account_type)
        setName(username)
        setToken(response.token)
        setAccount(response.account_type)
        resolve()
        this.getAsyncRouter()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 移除token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      removeName()
      removeAccount()
      removeButtonpermsStr()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

